<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>jQuery的数据缓存模块 | 个人博客 | 一个coder的成长记录</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="jQuery">
    <meta name="description" content="jQuery的数据缓存模块 几乎每一个前端库或者框架都有自己的数据缓存模块，而且这个是框架的基础核心模块。所有的应用模块，都会依赖这个数据缓存模块。jQuery也有自己的数据缓存模块，所以把自己学习的心得分享一下。  属性缓存数据 属性缓存数据，就是使用对象的属性或者element元素的attribute来缓存数据。jQuery（1.x）就是利用这个实现的自己的数据缓存模块的。这种方法也叫属性标记">
<meta name="keywords" content="jQuery">
<meta property="og:type" content="article">
<meta property="og:title" content="jQuery的数据缓存模块">
<meta property="og:url" content="https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="jQuery的数据缓存模块 几乎每一个前端库或者框架都有自己的数据缓存模块，而且这个是框架的基础核心模块。所有的应用模块，都会依赖这个数据缓存模块。jQuery也有自己的数据缓存模块，所以把自己学习的心得分享一下。  属性缓存数据 属性缓存数据，就是使用对象的属性或者element元素的attribute来缓存数据。jQuery（1.x）就是利用这个实现的自己的数据缓存模块的。这种方法也叫属性标记">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-04-12T09:42:14.470Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="jQuery的数据缓存模块">
<meta name="twitter:description" content="jQuery的数据缓存模块 几乎每一个前端库或者框架都有自己的数据缓存模块，而且这个是框架的基础核心模块。所有的应用模块，都会依赖这个数据缓存模块。jQuery也有自己的数据缓存模块，所以把自己学习的心得分享一下。  属性缓存数据 属性缓存数据，就是使用对象的属性或者element元素的attribute来缓存数据。jQuery（1.x）就是利用这个实现的自己的数据缓存模块的。这种方法也叫属性标记">
    
        <link rel="alternate" type="application/atom+xml" title="个人博客" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide">
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">俊男</h5>
          <a href="mailto:betgar@163.com" title="betgar@163.com" class="mail">betgar@163.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/">
                <i class="icon icon-lg icon-home"></i>
                Home
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives">
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags">
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories">
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/betgar" target="_blank">
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/u/2296734915" target="_blank">
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about">
                <i class="icon icon-lg icon-link"></i>
                About
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">jQuery的数据缓存模块</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">jQuery的数据缓存模块</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-05-31T12:00:00.000Z" itemprop="datePublished" class="page-time">
  2017-05-31
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/jQuery/">jQuery</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#jQuery的数据缓存模块"><span class="post-toc-number">1.</span> <span class="post-toc-text">jQuery的数据缓存模块</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#属性缓存数据"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">属性缓存数据</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#数据缓存模块实现原理"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">数据缓存模块实现原理</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#jQuery数据缓存模块源码"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">jQuery数据缓存模块源码</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#HTML5的DataSet-API"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">HTML5的DataSet API</span></a></li></ol></li></ol>
        </nav>
    </aside>


<article id="post-the-data-storage-module-of-jquery" class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">jQuery的数据缓存模块</h1>
        <div class="post-meta">
            <time class="post-time" title="2017-05-31 20:00:00" datetime="2017-05-31T12:00:00.000Z" itemprop="datePublished">2017-05-31</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/jQuery/">jQuery</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style="display:none">
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="jQuery的数据缓存模块"><a href="#jQuery的数据缓存模块" class="headerlink" title="jQuery的数据缓存模块"></a>jQuery的数据缓存模块</h1><blockquote>
<p>几乎每一个前端库或者框架都有自己的数据缓存模块，而且这个是框架的基础核心模块。所有的应用模块，都会依赖这个数据缓存模块。jQuery也有自己的数据缓存模块，所以把自己学习的心得分享一下。</p>
</blockquote>
<h2 id="属性缓存数据"><a href="#属性缓存数据" class="headerlink" title="属性缓存数据"></a>属性缓存数据</h2><blockquote>
<p>属性缓存数据，就是使用对象的属性或者element元素的attribute来缓存数据。jQuery（1.x）就是利用这个实现的自己的数据缓存模块的。这种方法也叫<strong>属性标记法</strong>.</p>
</blockquote>
<ol>
<li><p>element属性attribute标记法</p>
<blockquote>
<p>这个写过前端代码的都很熟悉，就是在标签的html上加上自定义属性。</p>
</blockquote>
<p>栗子1：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- element-attribute.html --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"demo1"</span> <span class="attr">customize</span>=<span class="string">"defined by me"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"getAttrBtn"</span>&gt;</span>getAttr<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"setAttrBtn"</span>&gt;</span>setAttr<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> $ = <span class="function"><span class="keyword">function</span> (<span class="params">id</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">document</span>.getElementById(id);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> getAttrBtn = $(<span class="string">'getAttrBtn'</span>);</span><br><span class="line"><span class="keyword">var</span> setAttrBtn = $(<span class="string">'setAttrBtn'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *标签属性标记法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">getAttrBtn.onclick = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> demoEle = $(<span class="string">'demo1'</span>), value = demoEle.getAttribute(<span class="string">'customize'</span>);</span><br><span class="line">  <span class="built_in">window</span>.console.log(value);</span><br><span class="line">  demoEle.innerHTML = value;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">setAttrBtn.onclick = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> demoEle = $(<span class="string">'demo1'</span>),value;</span><br><span class="line">  demoEle.setAttribute(<span class="string">'customize'</span>, <span class="string">'changed by element attribute'</span>);</span><br><span class="line">  value = demoEle.getAttribute(<span class="string">'customize'</span>);</span><br><span class="line">  <span class="built_in">window</span>.console.log(value);</span><br><span class="line">  demoEle.innerHTML = value;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>栗子1就是我们通过element标签来保存一些自己的业务数据。</p>
<p>优点：原生；所有浏览器都支持。</p>
<p>缺点：只能保存<strong>字符串</strong>，不能保存<strong>对象</strong>和<strong>function</strong>，这两种类型。</p>
<p>​</p>
</li>
<li><p>对象属性标记法</p>
<blockquote>
<p>对象属性标记，就很好理解了，就是平时我们给JavaScript对象赋值的操作。</p>
</blockquote>
<p>栗子2：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- element-attribute.html --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"demo1"</span> <span class="attr">customize</span>=<span class="string">"defined by me"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"getAttrBtn"</span>&gt;</span>getAttr<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"setAttrBtn"</span>&gt;</span>setAttr<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>​</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">*对象属性标记法</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">getAttrBtn.ondblclick = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> demoEle = $(<span class="string">'demo1'</span>), value = demoEle[<span class="string">'customize'</span>];</span><br><span class="line">  <span class="built_in">window</span>.console.log(value);</span><br><span class="line">  demoEle.innerHTML = value;</span><br><span class="line">&#125;;</span><br><span class="line">setAttrBtn.ondblclick = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> demoEle = $(<span class="string">'demo1'</span>),value;</span><br><span class="line">  demoEle[<span class="string">'customize'</span>] = <span class="string">'changed by object attribute'</span>,value = demoEle[<span class="string">'customize'</span>];</span><br><span class="line">  <span class="built_in">window</span>.console.log(value);</span><br><span class="line">  demoEle.innerHTML = value;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>栗子2就是对象属性标记法，原理就是直接使用浏览器中element(宿主元素)进行数据缓存。</p>
<p>优点：JavaScript全类型的数据都支持。</p>
<p>缺点：</p>
<ul>
<li><p>浏览器兼容性问题。</p>
</li>
<li><p>object,applet,embed等对象是不能使用这种方法，进行属性缓存数据，因为他们不是标准的浏览器中的对象，属于扩展内容。</p>
</li>
<li><p>window对象如果使用这种方式，变成了全局变量</p>
</li>
<li><p><strong>内存泄漏</strong>：内存泄漏是这种方式的最大威胁。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 内存泄漏栗子：</span></span><br><span class="line"><span class="comment">// 最直接的栗子就是demoEle.dep.el的属性指向demoEle</span></span><br><span class="line"><span class="keyword">var</span> demoEle = $(<span class="string">'demo1'</span>);</span><br><span class="line">demoEle.dep = &#123;</span><br><span class="line">  el: demoEle</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 这样的循环依赖，很难觉察到，所以demoEle.dep和demoEle都得不到回收，造成内存泄漏。</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ol>
<h2 id="数据缓存模块实现原理"><a href="#数据缓存模块实现原理" class="headerlink" title="数据缓存模块实现原理"></a>数据缓存模块实现原理</h2><blockquote>
<p>属性缓存数据的两种方法，各有优缺点，但是<strong>对象属性缓存数据</strong> 已经非常理想了，只要解决一下<strong>内存泄漏</strong> 这个问题就很实用了。分享一下jQuery的巧妙设计。</p>
</blockquote>
<p>jQuery的设计思路：</p>
<ul>
<li>数据统一管理（数据储存在一个<strong>对象</strong> 中）</li>
<li>数据不缓存在具体的element对象属性上，而是在element缓存一个jQueryKey，然后通过jQueryKey存取数据。</li>
</ul>
<blockquote>
<p>jQueryKey：是一个字符串值，不存在<strong>循环依赖</strong> 解决<strong>内存泄漏</strong>的问题 。</p>
</blockquote>
<p>栗子：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- data-storage.html --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"demo1"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"getAttrBtn"</span>&gt;</span>getStore<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"setAttrBtn"</span>&gt;</span>store<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isNumeric</span>(<span class="params">obj</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> !<span class="built_in">isNaN</span>(<span class="built_in">parseFloat</span>(obj)) &amp;&amp; <span class="built_in">isFinite</span>(obj);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Model</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">Model.cacheKey = <span class="string">'ceche'</span> + (<span class="keyword">new</span> <span class="built_in">Date</span>).getTime();</span><br><span class="line">Model.cache = &#123;&#125;; <span class="comment">// 用来缓存数据</span></span><br><span class="line">Model.uuid = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">Model.data = <span class="function"><span class="keyword">function</span> (<span class="params">ele, key, value</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> cacheKey = Model.cacheKey, indexKey = ele[cacheKey];</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">arguments</span>.length === <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="comment">// get </span></span><br><span class="line">    <span class="keyword">if</span> (isNumeric(indexKey)) &#123;</span><br><span class="line">      <span class="keyword">return</span> Model.cache[indexKey][key] === <span class="literal">undefined</span> ? <span class="literal">null</span> </span><br><span class="line">      						: Model.cache[indexKey][key];</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// set</span></span><br><span class="line">    <span class="keyword">if</span> (isNumeric(indexKey)) &#123;</span><br><span class="line">      Model.cache[indexKey][key] = value;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      ele[cacheKey] = indexKey = <span class="string">''</span> + Model.uuid++;</span><br><span class="line">      Model.cache[indexKey] = &#123;&#125;;</span><br><span class="line">      Model.cache[indexKey][key] = value;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;  </span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>上面的栗子：</p>
<p>Model.cacheKey做element的属性，element[Model.cacheKey]的value值是Model.cache的对象key。</p>
<ul>
<li>element[Model.cacheKey]的value值，只是一个字符串所以，完美解决了<strong>内存泄漏</strong> 问题。</li>
<li>Model.cache是一个普通的JavaScript对象，所以它可以支持所有的JavaScript的数据类型。解决了在标签的属性上缓存数据，只支持 <strong>字符串</strong> 的问题。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这就是element对应cache中缓存的整个数据对象</span></span><br><span class="line">Model.cache[element[Model.cacheKey]];</span><br></pre></td></tr></table></figure>
<h2 id="jQuery数据缓存模块源码"><a href="#jQuery数据缓存模块源码" class="headerlink" title="jQuery数据缓存模块源码"></a>jQuery数据缓存模块源码</h2><blockquote>
<p>jQuery数据缓存模块的部分源码。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 下面的就是一些 jQuery 涉及数据存储的操作</span></span><br><span class="line">jQuery.extend(&#123;</span><br><span class="line">  <span class="comment">// 全局的缓存对象</span></span><br><span class="line">  cache: &#123;&#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// The following elements throw uncatchable exceptions if you</span></span><br><span class="line">  <span class="comment">// attempt to add expando properties to them.</span></span><br><span class="line">  <span class="comment">// 如果你尝试给以下元素添加扩展属性,将抛出“无法捕捉”的异常</span></span><br><span class="line">  <span class="comment">// 这里声明的几个元素对象是不给于数据绑定的</span></span><br><span class="line">  <span class="comment">// applet、embed 和 object 元素是不支持设置 expando 属性的，所以不支持 data 方法</span></span><br><span class="line">  noData: &#123;</span><br><span class="line">    <span class="string">"applet"</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="string">"embed"</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="comment">// Ban all objects except for Flash (which handle expandos)</span></span><br><span class="line">    <span class="string">"object"</span>: <span class="string">"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 检查对象是否已经存储了数据</span></span><br><span class="line">  hasData: <span class="function"><span class="keyword">function</span>(<span class="params">elem</span>) </span>&#123;</span><br><span class="line">    elem = elem.nodeType ? jQuery.cache[elem[jQuery.expando]] : elem[jQuery.expando];</span><br><span class="line">    <span class="keyword">return</span> !!elem &amp;&amp; !isEmptyDataObject(elem);</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 给 elem（可是DOM，可以是JS对象）添加 key-value 为 name-data 的数据</span></span><br><span class="line">  data: <span class="function"><span class="keyword">function</span>(<span class="params">elem, name, data</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> internalData(elem, name, data);</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 移除 elem（可是DOM，可以是JS对象）上</span></span><br><span class="line">  removeData: <span class="function"><span class="keyword">function</span>(<span class="params">elem, name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> internalRemoveData(elem, name);</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// For internal use only.</span></span><br><span class="line">  <span class="comment">// 添加或读取一个仅供内部使用的数据</span></span><br><span class="line">  _data: <span class="function"><span class="keyword">function</span>(<span class="params">elem, name, data</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> internalData(elem, name, data, <span class="literal">true</span>);</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 删除内部使用的数据数据</span></span><br><span class="line">  _removeData: <span class="function"><span class="keyword">function</span>(<span class="params">elem, name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> internalRemoveData(elem, name, <span class="literal">true</span>);</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// A method for determining if a DOM node can handle the data expando</span></span><br><span class="line">  <span class="comment">// 检测一个属性是否可以绑定数据</span></span><br><span class="line">  <span class="comment">// nodeType = 1 -- Element</span></span><br><span class="line">  <span class="comment">// nodeType = 9 -- Document</span></span><br><span class="line">  acceptData: <span class="function"><span class="keyword">function</span>(<span class="params">elem</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// Do not set data on non-element because it will not be cleared (#8335).</span></span><br><span class="line">    <span class="comment">// </span></span><br><span class="line">    <span class="keyword">if</span> (elem.nodeType &amp;&amp; elem.nodeType !== <span class="number">1</span> &amp;&amp; elem.nodeType !== <span class="number">9</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// if(elem.nodeName)&#123;</span></span><br><span class="line">    <span class="comment">//   noData = jQuery.noData[elem.nodeName.toLowerCase()];</span></span><br><span class="line">    <span class="comment">// &#125;</span></span><br><span class="line">    <span class="keyword">var</span> noData = elem.nodeName &amp;&amp; jQuery.noData[elem.nodeName.toLowerCase()];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// nodes accept data unless otherwise specified; rejection can be conditional</span></span><br><span class="line">    <span class="keyword">return</span> !noData || noData !== <span class="literal">true</span> &amp;&amp; elem.getAttribute(<span class="string">"classid"</span>) === noData;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>来一个对应：</p>
<ul>
<li>jQuery.expando对应Model.cacheKey</li>
<li>jQuery.cache对应Model.cache</li>
<li>jQuery.data对应Model.data</li>
</ul>
<p>在jQuery.hasData方法内部看到了：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jQuery.cache[elem[jQuery.expando]]; <span class="comment">// 取数据</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Model.cache[indexKey][key]; <span class="comment">// Model和jQuery原理是一样的。</span></span><br></pre></td></tr></table></figure>
<p>有了Model这个小栗子，就能更好的理解jQuery的data模块实现原理了；当然jQuery的data模块还有很多其它的兼容性处理，防冲突处理。</p>
<h2 id="HTML5的DataSet-API"><a href="#HTML5的DataSet-API" class="headerlink" title="HTML5的DataSet API"></a>HTML5的DataSet API</h2><blockquote>
<p>HTML5加入了一个关于自定义属性的API，很是方便，虽然非现代浏览器不支持，但是你可以使用jQuery，jQuery已经提供了支持。</p>
</blockquote>
<p>栗子：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 自定义属性使用 data-* 开头 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">span</span> <span class="attr">data-toggle</span>=<span class="string">"dropdown"</span> <span class="attr">class</span>=<span class="string">"moduleTitle"</span> <span class="attr">data-options</span>=<span class="string">"234"</span>&gt;</span>测试<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 原生操作</span></span><br><span class="line"><span class="comment">// 返回全部以data-开头的自定义属性.</span></span><br><span class="line"><span class="keyword">var</span> dataSet = <span class="built_in">document</span>.querySelector(<span class="string">'.moduleTitle'</span>).dataset; <span class="comment">// DOMStringMap</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 返回options</span></span><br><span class="line"><span class="keyword">var</span> dataSet = <span class="built_in">document</span>.querySelector(<span class="string">'.moduleTitle'</span>).dataset.options;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 新增或者修改(同步DOM元素的data-options属性)</span></span><br><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'.moduleTitle'</span>).dataset.options = <span class="number">234</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 删除</span></span><br><span class="line"><span class="keyword">delete</span> <span class="built_in">document</span>.querySelector(<span class="string">'.moduleTitle'</span>).dataset.options</span><br></pre></td></tr></table></figure>
<p>jQuery栗子：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">span</span> <span class="attr">data-toggle</span>=<span class="string">"dropdown"</span> <span class="attr">class</span>=<span class="string">"moduleTitle"</span> <span class="attr">data-options</span>=<span class="string">"234"</span></span></span><br><span class="line"><span class="tag">      <span class="attr">data-camel-options</span>=<span class="string">"234"</span>&gt;</span>测试<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// jQuery操作</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 访问所有的缓存数据，包括data-*自定义部分</span></span><br><span class="line"><span class="keyword">var</span> dataSet = $(<span class="string">'.moduleTitle'</span>).data();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 查询 （jQuery为了遵守规范自动转换data-*自定义属性为“驼峰”访问方式.）</span></span><br><span class="line"><span class="keyword">var</span> camelOptions = $(<span class="string">'.moduleTitle'</span>).data(<span class="string">'camelOptions'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 修改 (jQuery使用自己数据缓存模块，不再同步修改data-camel-options属性)</span></span><br><span class="line">$(<span class="string">'.moduleTitle'</span>).data(<span class="string">'camelOptions'</span>, <span class="number">3</span>);</span><br><span class="line">$(<span class="string">'.moduleTitle'</span>).data(<span class="string">'camelOptions'</span>); <span class="comment">// 3</span></span><br><span class="line">$(<span class="string">'.moduleTitle'</span>).attr(<span class="string">'data-camel-options'</span>); <span class="comment">// 234</span></span><br></pre></td></tr></table></figure>
<p>注意：</p>
<blockquote>
<p>​       jQuery.data访问data-<em>自定义属性是有优先级顺序，先从$.cache中获取，如果没有，才尝试自定义属性获取。<br>​       jQuery.data方法只能修改自己缓存内的数据，不会修改data-</em>属性的数据；所以千万不要使用jQuery().attr和jQuery.data混合使用操作data-自定义属性。</p>
</blockquote>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-04-12T09:42:14.470Z" itemprop="dateUpdated">2019-04-12 17:42:14</time>
</span><br>


        
        原文链接：<a href="/2017/05/31/the-data-storage-module-of-jquery/" target="_blank" rel="external">https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/</a>
        
    </div>
    
    <footer>
        <a href="https://betgar.github.io">
            <img src="/img/avatar.jpg" alt="俊男">
            俊男
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/jQuery/">jQuery</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/&title=《jQuery的数据缓存模块》 — 个人博客&pic=https://betgar.github.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/&title=《jQuery的数据缓存模块》 — 个人博客&source=各种技术加身的coder" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《jQuery的数据缓存模块》 — 个人博客&url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/&via=https://betgar.github.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/11/23/how-to-use-oracle-reference/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">怎么使用Oracle手册</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/05/07/building-stateful-plugins-with-jquery-ui-widget/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">使用jQuery UI widget编写有状态的插件</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "kiGWA9mdoVtQlfGYA5uDBNX7-gzGzoHsz",
            appKey: "dHCOdD0oEIjJd0cJoAHHN0y3",
            avatar: "mm",
            placeholder: "Just comment it",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style="display:none">
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style="display:none">
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>俊男 &copy; 2017 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/&title=《jQuery的数据缓存模块》 — 个人博客&pic=https://betgar.github.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/&title=《jQuery的数据缓存模块》 — 个人博客&source=各种技术加身的coder" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《jQuery的数据缓存模块》 — 个人博客&url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/&via=https://betgar.github.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://betgar.github.io/2017/05/31/the-data-storage-module-of-jquery/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
